import {SetDownloaderLib} from "./SetDownloaderLib";
import {GeneratorFactory} from "../executor/GeneratorFactory";
import {GeneratorExecutor} from "../executor/GeneratorExecutor";
import moment from 'moment'
import {SqlLib} from "../sqlite/SqlLib";
import {SqlLibUser} from "../sqlite/service/SqlLibUser";
import {Downloader} from "../sqlite/model/Downloader";
import {Downloaded} from "../sqlite/model/Downloaded";
import {UserResource} from "../sqlite/model/UserResource";
import {SqlLibBook} from "../sqlite/service/SqlLibBook";
import {UUIDUtil} from "../../utils/UUIDUtil";
import {ThumbDownloader} from "./ThumbDownloader";
import {Lesson} from "../sqlite/model/Lesson";
import {User} from "../sqlite/model/User";

export class DownloadCenter {

    constructor() {
        this.setDownloaders = [];//下载器对象,增加几个状态值：0-初始化成功；1-初始化失败；2-正在下载中；3-已经暂停；4-下载失败(centerStatus)；5-未初始化（针对全书下载）
        // this.currentDownloadIndex = [];//当前正在下载的索引
        this.downloaded = [];//已经下载完成的数据 对象数组，对象例子：{lessonId: "", lessonName: "", endTime: "", status: ""}
        this.downloadingSize = 2;//允许同时下载的个数
        // this.initErrorIndex = [];//初始化错误的索引数组
        //视图层 正在下载中的图表
        this.downloadingTable = [];
        this.request = null;
        this.constVar = null;
        this.vueInstance = null;
        this.initCenterMap = new Map();
    }

    //单例调用，全局只有这一个实例
    static getInstance(vueInstance) {
        if (!this.instance) {
            let _this = this;
            //初始化下载器数组 & 已经下载过的数组
            let completeDown = new Downloaded();
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let user = SqlLibUser.queryCurrentUser(sqlLib);
            completeDown.userId = user.id;
            let result = sqlLib.selectAllObjectByKeys(completeDown, ["userId"]);
            let curDownloaded = [];
            result.forEach(complete => {
                if (complete.downloadedJson) {
                    curDownloaded.push(JSON.parse(complete.downloadedJson));
                }
            });
            let unCompletes = SqlLibBook.queryUnDownloadLesson(sqlLib);
            let downloadParams = [];
            unCompletes.forEach(unComplete => {
                if (unComplete.downloadParam) {
                    downloadParams.push(JSON.parse(unComplete.downloadParam));
                }
            });
            this.instance = new DownloadCenter();
            if(vueInstance){
                this.instance.vueInstance = vueInstance;
            }
            this.instance.downloaded = curDownloaded;
            // if(downloadParams.length > 0){
            //     if(user.vipType === "0"){//只有SVIP才给恢复下载功能
            //         _this.instance.syncPushDownloadCenter(downloadParams, function () {
            //             console.log("下载中心列表已经恢复！");
            //         });
            //         _this.instance.initDownloadingTable();
            //     }
            // }
        }
        return this.instance;
    }

    static removeInstance(){
        if(this.instance){
            this.instance = null;
        }
    }

    /**
     * 同步塞入下载中心，不需要初始化
     * @param downloadParams
     * @param callback 如果用户塞入callback参数，则不进行后续的下载操作，让用户选择性触发
     */
    syncPushDownloadCenter(downloadParams, callback) {
        let _this = this;
        console.log("syncPushDownloadCenter:: pre setDownloaders", _this.setDownloaders);
        let initId = UUIDUtil.uuid();
        let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
        if (downloadParams.length > 0) {
            let promiseArr = [];
            downloadParams.forEach(param => {
                if(!_this.lessonIsDownloading(param.SetDownloadId) && _this.isDownloaderAlowed(param)){//check当前课时是否正在下载
                    _this.setDownloaders.push({
                        downloaderId: param.SetDownloadId,
                        downloaderInfo: param.DownloaderInfo,
                        centerStatus: 5, //未初始化
                        actionStatus: param.ActionStatus
                    });
                    let currentDownloader = _this.setDownloaders[_this.setDownloaders.length - 1];
                    DownloadCenter.getInstance().changeViewTables(currentDownloader, "add");
                    if (param.DownloadParams) {//代表是单个课时的下载
                        let initSetDownloader = function () {
                            return new Promise((resolve, reject) => {
                                setTimeout(function () {
                                    let tempParam = JSON.stringify(param);
                                    let setDownloader = new SetDownloaderLib(param, function () {
                                        setDownloader.centerStatus = 0;//初始化成功
                                        setDownloader.actionStatus = param.ActionStatus
                                        _this.replaceDownloader(setDownloader);
                                        DownloadCenter.getInstance().changeViewTables(setDownloader, "change");
                                        if(callback){//如果传了callback ，默认只初始化，不去下载
                                        }else {
                                            DownloadCenter.getInstance().initDownloadCenter();
                                        }
                                        console.log("1.初始化成功！ id::>" + setDownloader.downloaderId);
                                        try {
                                            let downloader = new Downloader();
                                            downloader.id = param.SetDownloadId;
                                            downloader.downloadParam = tempParam;
                                            downloader.userId = user.id;
                                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                                        } catch (e) {
                                            console.log(e);
                                        }
                                        //异步去下载缩略图
                                        ThumbDownloader.asyncDownloadThumbs(_this.request, setDownloader.downloadParames);
                                        resolve("success");
                                    }, function () {
                                        setDownloader.centerStatus = 1;//初始化失败
                                        setDownloader.actionStatus = param.ActionStatus
                                        _this.replaceDownloader(setDownloader);
                                        DownloadCenter.getInstance().changeViewTables(setDownloader, "change");
                                        try {
                                            let downloader = new Downloader();
                                            downloader.id = param.SetDownloadId;
                                            downloader.downloaderStatus = "1";
                                            downloader.userId = user.id;
                                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                                        } catch (e) {
                                            console.log(e);
                                        }
                                        console.log("1.初始化失败！ id::>" + setDownloader.downloaderId);
                                        reject("error");
                                    });
                                }, 1000);
                            });
                        }
                        promiseArr.push(initSetDownloader);
                    } else {//代表是全书的下载，刚开始没拿到下载数据
                        let sqlLib = SqlLib.getInstance(window.$DBDIR);
                        let user = SqlLibUser.queryCurrentUser(sqlLib);
                        let initSetDownloader = function () {
                            return new Promise(((resolve, reject) => {
                                setTimeout(function () {
                                    DownloadCenter.getInstance().getResAndCoueseware(user.id, param.SetDownloadId, function (lessonItems, itemBsr, isResourceEmpty) {
                                        if (!isResourceEmpty) {
                                            DownloadCenter.getInstance().request.getResourceInfoByResIds({
                                                metaParamDTOS: itemBsr
                                            }).then(response => {
                                                let bsrResources = response.returnValue.resources;
                                                let currentParams = []
                                                lessonItems.forEach((item, index) => {
                                                    if (bsrResources[item.id]) {
                                                        let bsr = bsrResources[item.id];
                                                        bsr.brief = item.brief ? item.brief : "";
                                                        bsr.intro = item.intro ? item.intro : "";
                                                        bsr.scenarios = item.scenarios ? item.scenarios : "";
                                                        bsr.meta_info.name = item.name;
                                                        item.downloadInfo.Bsr = JSON.stringify(bsr);
                                                    }
                                                    if (item.downloadInfo.FileType === "courseware") {
                                                        item.downloadInfo.Bsr = JSON.stringify(item);
                                                    }
                                                    currentParams.push(item.downloadInfo);
                                                });
                                                //备份一份下载参数，方便入库
                                                let dbDownloadParams = JSON.stringify({
                                                    SetDownloadId: param.SetDownloadId,
                                                    DownloaderInfo: param.DownloaderInfo,
                                                    DownloadParams: currentParams
                                                });
                                                let setDownloader = new SetDownloaderLib({
                                                    SetDownloadId: param.SetDownloadId,
                                                    DownloaderInfo: param.DownloaderInfo,
                                                    DownloadParams: currentParams
                                                }, function () {
                                                    setDownloader.centerStatus = 0;//初始化成功
                                                    setDownloader.actionStatus = param.ActionStatus
                                                    _this.replaceDownloader(setDownloader);
                                                    DownloadCenter.getInstance().changeViewTables(setDownloader, "change");
                                                    try {
                                                        let downloader = new Downloader();
                                                        downloader.id = param.SetDownloadId;
                                                        downloader.downloadParam = dbDownloadParams;
                                                        downloader.userId = user.id;
                                                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                                                    } catch (e) {
                                                        console.log(e);
                                                    }
                                                    //异步去下载缩略图
                                                    ThumbDownloader.asyncDownloadThumbs(_this.request, setDownloader.downloadParames);
                                                    console.log("1.全书课时初始化成功！ id::>" + setDownloader.downloaderId);
                                                    resolve("success");
                                                    DownloadCenter.getInstance().initDownloadCenter();
                                                }, function () {
                                                    setDownloader.centerStatus = 1;//初始化失败
                                                    DownloadCenter.getInstance().changeViewTables(setDownloader, "change");
                                                    try {
                                                        let downloader = new Downloader();
                                                        downloader.id = param.SetDownloadId;
                                                        downloader.downloaderStatus = "1";
                                                        downloader.downloadParam = JSON.stringify({
                                                            SetDownloadId: param.SetDownloadId,
                                                            DownloaderInfo: param.DownloaderInfo,
                                                            DownloadParams: currentParams
                                                        });
                                                        downloader.userId = user.id;
                                                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                                                    } catch (e) {
                                                        console.log(e);
                                                    }
                                                    console.log("1.全书课时初始化失败！ id::>" + setDownloader.downloaderId);
                                                    reject("error");
                                                });
                                            }).catch(error => {
                                                currentDownloader.centerStatus = 4;
                                                DownloadCenter.getInstance().changeViewTables(currentDownloader, "change");
                                                reject("error");
                                            })
                                        } else {
                                            //没有需要下载的资源，直接移除
                                            DownloadCenter.getInstance().removeDownloader(currentDownloader);
                                            DownloadCenter.getInstance().changeViewTables(currentDownloader, "remove");
                                            console.log("发送changeDownloadStatus 事件")
                                            let changeEvent = new CustomEvent('changeDownloadStatus', {
                                                detail: {
                                                    lessonId: currentDownloader.downloaderId,
                                                    actionStatus: currentDownloader.actionStatus
                                                }
                                            });
                                            window.dispatchEvent(changeEvent);
                                            resolve("success");
                                        }
                                    }, function () {
                                        currentDownloader.centerStatus = 4;
                                        DownloadCenter.getInstance().changeViewTables(currentDownloader, "change");
                                        reject("error");
                                    });
                                }, 1000);
                            }));
                        }
                        promiseArr.push(initSetDownloader);
                    }
                }
            });
            console.log("syncPushDownloadCenter:: after setDownloaders", _this.setDownloaders);

            let gen = GeneratorFactory.createGenerator(promiseArr);
            let executor = new GeneratorExecutor();
            _this.initCenterMap.set(initId, executor);
            executor.run(gen, function () {
                if(_this.initCenterMap.has(initId)){
                    _this.initCenterMap.delete(initId);
                }
                if(callback){//如果传了callback ，默认只初始化，不去下载
                    callback();
                }else {
                    DownloadCenter.getInstance().initDownloadCenter();
                }
            });
        }
    }

    /**
     * 从服务端获取资源数据，用于全书下载，刚开始没有数据初始化
     * @param userId
     * @param lessonId
     * @param callback
     */
    getResAndCoueseware(userId, lessonId, callback, errorCallback) {
        let _this = this;
        _this.request.getResAndCouesewareByLessonId({
            lessonId: lessonId
        }).then(response => {
            let result = [];
            let resultBsr = [];
            let resAndCouse = response.returnValue;
            let isResourceEmpty = false;
            if (resAndCouse.resCoursewaresVOList && resAndCouse.resCoursewaresVOList.length && resAndCouse.resCoursewaresVOList.length > 0) {
                resAndCouse.resCoursewaresVOList.forEach((course, index) => {
                    let courseObj = {
                        id: course.id,
                        name: course.title,
                        resType: "课时PPT",
                        tag: course.tag === "twig" ? 1 : 0, //0 - 美丽科学；1 - twig
                        thumb: course.thumb,
                        downloadInfo: {
                            FileName: course.id + ".ppt",
                            FileType: "courseware",
                            TaskId: course.id,
                            Url: course.url
                        }
                    };
                    if (index === 0) {
                        courseObj.isDefault = "1";
                    } else {
                        courseObj.isDefault = "0";
                    }
                    result.push(courseObj);
                    resultBsr.push({
                        metaId: course.id,
                        metaType: "courseware"
                    });
                });
            }
            if (resAndCouse.resourceVOList && resAndCouse.resourceVOList.length && resAndCouse.resourceVOList.length > 0) {
                let quizes = [];
                resAndCouse.resourceVOList.forEach(resource => {
                    let info = {
                        id: resource.resMetaInfoVO.meta_id,
                        name: resource.name,
                        resType: '课时资源 | ' + DownloadCenter.getInstance().resTypeToName(resource.resMetaInfoVO.res_type),
                        tag: resource.tag === "twig" ? 1 : 0,//0 - 美丽科学；1 - twig
                        thumb: resource.resMetaInfoVO.thumb,
                        brief: resource.brief ? resource.brief : "",
                        intro: resource.intro ? resource.intro : "",
                        scenarios: resource.scenarios ? resource.scenarios : "",
                        downloadInfo: {
                            TaskId: resource.resMetaInfoVO.meta_id,
                            FileType: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type),
                            FileName: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type) === "PolyvVideo" ? resource.resMetaInfoVO.meta_id : resource.resMetaInfoVO.meta_id + ".zip",
                            Url: resource.resMetaInfoVO.zip_url ? DownloadCenter.getInstance().constVar.global.cdnResourcePrefix + resource.resMetaInfoVO.zip_url : ""
                        }
                    }
                    resultBsr.push({
                        metaId: resource.resMetaInfoVO.meta_id,
                        metaType: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type)
                    })
                    if (DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type) == "Quiz") {
                        quizes.push(info);
                    } else {
                        result.push(info);
                    }
                });
                result = result.concat(quizes);
            }
            if(!resAndCouse.resourceVOList && !resAndCouse.resCoursewaresVOList){
                isResourceEmpty = true;
            }else {
                if((resAndCouse.resCoursewaresVOList instanceof Array && resAndCouse.resCoursewaresVOList.length === 0) &&
                    (resAndCouse.resourceVOList instanceof Array && resAndCouse.resourceVOList.length === 0)){
                    isResourceEmpty = true;
                }
            }
            if (callback) {
                callback(result, resultBsr, isResourceEmpty);
            }
        }).catch(error => {
            if (errorCallback) {
                errorCallback();
            }
            console.log(error);
        })
    }

    /**
     * 私有方法，方便替换数组中的setDownloader
     * @param setDownloader
     */
    replaceDownloader(setDownloader) {
        let _this = this;
        let index = -1;
        _this.setDownloaders.forEach((downloader, i) => {
            if (downloader.downloaderId === setDownloader.downloaderId) {
                index = i;
            }
        });
        if (index !== -1) {
            _this.setDownloaders.splice(index, 1, setDownloader);
        }
    }

    /**
     * 根据downloader的变化，改变视图层
     * @param setDownloader
     * @param method  :  add   remove   change
     * @param progress  进度
     */
    changeViewTables(setDownloader, method, progress) {
        let _this = this;
        let downloadInfo = setDownloader.downloaderInfo;
        if(downloadInfo){
            if (method === "add") {
                _this.downloadingTable.push({
                    name: downloadInfo.lessonName,
                    publisher: downloadInfo.publisherName,
                    book: downloadInfo.bookName,
                    id: setDownloader.downloaderId,
                    status: setDownloader.centerStatus,
                    progress: {speed: 0, progressVal: 0},
                    isChecked: false
                });
            } else {
                let curIndex = -1
                _this.downloadingTable.forEach((table, index) => {
                    if (table.id === setDownloader.downloaderId) {
                        curIndex = index;
                    }
                });

                if (method === "remove") {
                    if (curIndex !== -1) {
                        _this.downloadingTable.splice(curIndex, 1);
                    }
                } else if (method === "change") {
                    let isChecked = _this.downloadingTable[curIndex].checked;
                    _this.downloadingTable.splice(curIndex, 1, {
                        name: downloadInfo.lessonName,
                        publisher: downloadInfo.publisherName,
                        book: downloadInfo.bookName,
                        id: setDownloader.downloaderId,
                        status: setDownloader.centerStatus,
                        progress: progress ? progress : {speed: 0, progressVal: 0},
                        checked: isChecked ? isChecked : false
                    });
                }
            }
        }
    }

    /**
     * 初始化下载中心
     */
    initDownloadCenter() {
        let _this = this;
        let currentIndex = DownloadCenter.getInstance().findDownloadingIndex();
        let startNum = this.downloadingSize - currentIndex.length;
        if (startNum <= 0) {
            return;
        } else {
            let requireDownloader = DownloadCenter.getInstance().findNextDownloadDownloader(startNum);
            requireDownloader.forEach(tempDownloader => {
                //赋值下载中
                tempDownloader.centerStatus = 2;
                DownloadCenter.getInstance().changeViewTables(tempDownloader, "change");
                tempDownloader.startDownload(function (successCallbackVal) {
                    let downloadInfo = tempDownloader.downloaderInfo;
                    let action = tempDownloader.actionStatus
                    if (action) {
                        if (action === "0") {
                            action = "下载完成"
                        } else if (action === "1") {
                            action = "更新完成"
                        } else if (action === "2") {
                            action = "同步完成"
                        }
                    } else {
                        action = "下载完成"
                    }
                    let downloadedJson = {
                        lessonId: tempDownloader.downloaderId,
                        lessonName: (downloadInfo && downloadInfo.lessonName) ? downloadInfo.lessonName : '',
                        bookName: (downloadInfo && downloadInfo.bookName) ? downloadInfo.bookName : '',
                        publisherName: (downloadInfo && downloadInfo.publisherName) ? downloadInfo.publisherName : '',
                        endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                        status: action
                    }
                    try {
                        //更新待下载列表
                        let downloader = new Downloader();
                        downloader.id = tempDownloader.downloaderId;
                        downloader.downloaderStatus = "2";
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);

                        let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                        //改变下载完成的课时状态
                        if(tempDownloader.errorDownloadTaskIndexes.length > 0){
                            downloadedJson.status = "部分成功"
                        }
                        //更新已完成列表
                        let complete = new Downloaded();
                        complete.downloadedJson = JSON.stringify(downloadedJson);
                        complete.completeTime = moment().format('YYYY-MM-DD HH:mm:ss');
                        complete.id = tempDownloader.downloaderId + "-" + user.id;
                        complete.reverse1 = tempDownloader.actionStatus;
                        complete.userId = user.id;
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(complete);

                        //更新用户资源关联列表
                        DownloadCenter.getInstance().saveOneLessonRes(tempDownloader).then(() => {
                            //触发一个改变单课时下载遮罩层的事件
                            console.log("发送changeDownloadStatus 事件")
                            let changeEvent = new CustomEvent('changeDownloadStatus', {
                                detail: {
                                    lessonId: tempDownloader.downloaderId,
                                    actionStatus: tempDownloader.actionStatus
                                }
                            });
                            window.dispatchEvent(changeEvent);
                        });
                    } catch (e) {
                        console.log(e);
                    }
                    DownloadCenter.getInstance().removeDownloader(tempDownloader);
                    DownloadCenter.getInstance().changeViewTables(tempDownloader, "remove");
                    let curIndex = -1;
                    _this.downloaded.forEach((download, index) => {
                        if(download.lessonId === downloadedJson.lessonId){
                            curIndex = index;
                        }
                    })
                    curIndex === -1 ? _this.downloaded.push(downloadedJson) : _this.downloaded.splice(curIndex, 1, downloadedJson);
                    //有一个下载成功，继续初始化下载中心，下载之后的课程
                    DownloadCenter.getInstance().initDownloadCenter();
                }, function () {
                    //赋值下载失败
                    tempDownloader.centerStatus = 4;
                    DownloadCenter.getInstance().changeViewTables(tempDownloader, "change");
                }, function (progressCallbackVal) {
                    tempDownloader.centerStatus = 2;
                    progressCallbackVal = JSON.parse(progressCallbackVal);
                    DownloadCenter.getInstance().changeViewTables(tempDownloader, "change", {
                        speed: progressCallbackVal.ReturnValue.DownloadSpeed,
                        progressVal: parseInt(progressCallbackVal.ReturnValue.Progress)
                    });
                });
            });
        }
    }

    /**
     * 删除某个固定的下载器
     * @param setDownloader
     */
    removeDownloader(setDownloader){
        let _this = this;
        let removeIndex = -1;
        _this.setDownloaders.forEach((downloader, index) => {
            if(downloader.downloaderId === setDownloader.downloaderId){
                removeIndex = index;
            }
        });
        if(removeIndex !== -1){
            _this.setDownloaders.splice(removeIndex, 1);
        }
    }

    /**
     * 保存一个课时的资源,同时删除该课程没有的资源
     * @param setDownloader
     */
    async saveOneLessonRes(setDownloader) {
        let downloadParams = setDownloader.downloadParames
        let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
        downloadParams.forEach((param, index) => {
            let userResource = new UserResource();
            userResource.id = UUIDUtil.uuid();
            userResource.userId = user.id;
            userResource.lessonId = setDownloader.downloaderId;
            userResource.resourceClassify = param.isLessonRes ? param.isLessonRes : "2";
            userResource.resourceType = param.FileType;
            let bsr = param.Bsr;
            if(bsr){
                bsr = JSON.parse(bsr);
                if(bsr.isDefault){
                    userResource.isDefault = bsr.isDefault;
                }else {
                    userResource.isDefault = "0"
                }
            }else {
                userResource.isDefault = "0"
            }
            userResource.resourceId = param.TaskId;
            userResource.resourceDescription = param.Bsr;
            userResource.resourceName = param.FileName;
            userResource.sortIndex = index + 1;
            if (setDownloader.errorDownloadTaskIndexes.length > 0
                && setDownloader.errorDownloadTaskIndexes.contains(index)) {
                userResource.downloadStatus = "1";
            } else {
                userResource.downloadStatus = "0";
            }
            SqlLibBook.updateOrInsertOneResource(SqlLib.getInstance(window.$DBDIR), userResource);
        });
        if(setDownloader.actionStatus && (setDownloader.actionStatus === "1" || setDownloader.actionStatus === "0")){//如果是更新的话,需要把版本号更新掉
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let lessonResource = SqlLibUser.queryLessonResource(sqlLib, user.id, setDownloader.downloaderId);
            if(lessonResource instanceof Array){
                if(lessonResource.length > 0){
                    let notExsist = [];
                    lessonResource.forEach(res => {
                        let result = false;
                        downloadParams.forEach(param => {
                            if(param.TaskId === res.resourceId || res.resourceClassify !== '2'){//只要存在，及为true
                                result = true;
                            }
                        })
                        if(!result){
                            notExsist.push(res);
                        }
                    });
                    notExsist.forEach(notExs => {
                        let tempL = new UserResource();
                        tempL.id = notExs.id;
                        sqlLib.deleteObjectById(tempL);
                    })
                }
            }
            let _this = this;
            let updateVersion = function(){
                return new Promise(resolve => {
                    _this.request.getLessonVersion({
                        lessonId: setDownloader.downloaderId
                    }).then(response => {
                        if(response.code == "0"){
                            let tempL = new Lesson();
                            tempL.id = setDownloader.downloaderId;
                            tempL = SqlLib.getInstance(window.$DBDIR).selectObjectById(tempL);
                            tempL.resVersion = response.returnValue.resVersion;
                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempL);
                        }
                        console.log("更新课程版本号...")
                        resolve("")
                    }).catch(e => {resolve("")})
                })
            }
            await updateVersion();
        }
    }

    /**
     * 从下载中心移除一组下载任务,不能移除正在下载的任务
     * @param downloadIds 下载任务的id数组
     */
    removeDownloadCenter(downloadIds) {
        let _this = this;
        let downloaders = [];
        let indexes = [];
        downloadIds.forEach(downloadId => {
            _this.setDownloaders.forEach((downloader, index) => {
                if (downloader.downloaderId === downloadId) {
                    downloaders.push(downloader);
                    indexes.push(index);
                }
            });
        });
        //删除downloader
        indexes.forEach(index => {
            _this.setDownloaders.splice(index, 1);
        });
        //删除视图
        downloaders.forEach(one => {
            DownloadCenter.getInstance().changeViewTables(one, "remove");
        });
    }


    /**
     * 暂停下载中心中的某几个下载任务, 只能暂停正在下载的任务
     * @param indexes
     * @param isNext 是否触发后续的下载，默认true , 如果是全部暂停，则不触发后续下载
     */
    pauseDownloadCenter(downloadIds, isNext = true) {
        let _this = this;
        if (downloadIds) {
            //批量暂停
            let downloaders = [];
            downloadIds.forEach(downloadId => {
                _this.setDownloaders.forEach((downloader, index) => {
                    if (downloader.downloaderId === downloadId) {
                        if (downloader.centerStatus === 2) {//如果正在下载就暂停下载
                            downloader.cancelDownload();
                        }
                        downloader.centerStatus = 3;//重新赋值为暂停状态
                        downloaders.push(downloader);
                    }
                });
            });
            //改变下载状态
            downloaders.forEach(downloader => {
                DownloadCenter.getInstance().changeViewTables(downloader, "change");
            })
            //暂停成功之后，重新初始化下载中心
            if(isNext){
                DownloadCenter.getInstance().initDownloadCenter();
            }
        }
    }

    /**
     * 暂停全部
     */
    pauseAlldownloader(){
        let downloadIds = [];

        //暂停所有的初始化操作
        this.initCenterMap.forEach((value, key) => {
            value.pause();
        });

        //暂停所有的下载器
        this.setDownloaders.forEach(downloader => {
            downloadIds.push(downloader.downloaderId);
        })
        this.pauseDownloadCenter(downloadIds, false);
        //清空列表
        this.setDownloaders.splice(0, this.setDownloaders.length);
        //不去除已经下载过的列表
        // this.downloaded.splice(0, this.downloaded.length);
        this.downloadingTable.splice(0, this.downloadingTable.length);
    }

    /**
     * 恢复单个未初始化的下载器，
     * @param downloadId
     */
    resumeUnInitDownloader(downloadId){
        console.log("触发 resumeUnInitDownloader...")
        let _this = this;
        if(downloadId){
            _this.setDownloaders.forEach(downloader => {
                if(downloader.downloaderId === downloadId){
                    if(downloader.centerStatus === 1 || downloader.centerStatus === 4 || downloader.centerStatus === 5){
                        downloader.centerStatus = 5;//重置为未初始化状态
                        DownloadCenter.getInstance().changeViewTables(downloader, "change");
                        setTimeout(function () {
                            let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                            DownloadCenter.getInstance().getResAndCoueseware(user.id, downloader.downloaderId, function (lessonItems, itemBsr, isResourceEmpty) {
                                if (!isResourceEmpty) {
                                    DownloadCenter.getInstance().request.getResourceInfoByResIds({
                                        metaParamDTOS: itemBsr
                                    }).then(response => {
                                        let bsrResources = response.returnValue.resources;
                                        let currentParams = []
                                        lessonItems.forEach((item, index) => {
                                            if (bsrResources[item.id]) {
                                                let bsr = bsrResources[item.id];
                                                bsr.brief = item.brief ? item.brief : "";
                                                bsr.intro = item.intro ? item.intro : "";
                                                bsr.scenarios = item.scenarios ? item.scenarios : "";
                                                bsr.meta_info.name = item.name;
                                                item.downloadInfo.Bsr = JSON.stringify(bsr);
                                            }
                                            if (item.downloadInfo.FileType === "courseware") {
                                                item.downloadInfo.Bsr = JSON.stringify(item);
                                            }
                                            currentParams.push(item.downloadInfo);
                                        });
                                        //备份一份下载参数，方便入库
                                        let dbDownloadParams = JSON.stringify({
                                            SetDownloadId: downloader.SetDownloadId,
                                            DownloaderInfo: downloader.DownloaderInfo,
                                            DownloadParams: currentParams
                                        });
                                        downloader = new SetDownloaderLib({
                                            SetDownloadId: downloader.downloaderId,
                                            DownloaderInfo: downloader.downloaderInfo,
                                            DownloadParams: currentParams
                                        }, function () {
                                            downloader.centerStatus = 0;//初始化成功
                                            downloader.actionStatus = downloader.ActionStatus
                                            _this.replaceDownloader(downloader);
                                            DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                            try {
                                                let tempDownloader = new Downloader();
                                                tempDownloader.id = downloader.downloaderId;
                                                tempDownloader.downloadParam = dbDownloadParams;
                                                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempDownloader);
                                            } catch (e) {
                                                console.log(e);
                                            }
                                            //异步去下载缩略图
                                            ThumbDownloader.asyncDownloadThumbs(_this.request, downloader.downloadParames);
                                            console.log("1.全书课时初始化成功！ id::>" + downloader.downloaderId);
                                            DownloadCenter.getInstance().initDownloadCenter();
                                        }, function () {
                                            setDownloader.centerStatus = 4;//初始化失败
                                            DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                            try {
                                                let tempDownloader = new Downloader();
                                                tempDownloader.id = downloader.downloaderId;
                                                tempDownloader.downloaderStatus = "1";
                                                tempDownloader.downloadParam = JSON.stringify({
                                                    SetDownloadId: downloader.downloaderId,
                                                    DownloaderInfo: downloader.downloaderInfo,
                                                    DownloadParams: currentParams
                                                });
                                                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempDownloader);
                                            } catch (e) {
                                                console.log(e);
                                            }
                                            console.log("1.全书课时初始化失败！ id::>" + setDownloader.downloaderId);
                                        });
                                    }).catch(error => {
                                        downloader.centerStatus = 4;
                                        DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                    })
                                }else {
                                    downloader.centerStatus = 0;//初始化成功
                                    downloader.actionStatus = downloader.ActionStatus
                                    _this.replaceDownloader(downloader);
                                    DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                }
                            }, function () {
                                downloader.centerStatus = 4;
                                DownloadCenter.getInstance().changeViewTables(downloader, "change");
                            });
                        }, 1000);
                    }
                }
            })
        }
    }

    /**
     * 恢复一组下载任务（针对已经初始化成功下载器，可恢复）
     * @param downloadIds
     */
    resumeDownloader(downloadIds) {
        let _this = this;
        if (downloadIds) {
            //批量暂停
            let downloaders = [];
            downloadIds.forEach(downloadId => {
                _this.setDownloaders.forEach((downloader, index) => {
                    if (downloader.downloaderId === downloadId) {
                        if (downloader.centerStatus !== 2) {//如果正在下载就不问了
                            downloader.centerStatus = 0;//重新赋值为初始化状态
                            downloaders.push(downloader);
                        }
                    }
                });
            });
            //改变下载状态
            downloaders.forEach(downloader => {
                DownloadCenter.getInstance().changeViewTables(downloader, "change");
            })
            //恢复成功之后，重新初始化下载中心
            DownloadCenter.getInstance().initDownloadCenter();
        }
    }

    findDownloadingIndex() {
        let currentDownloadIds = []
        this.setDownloaders.forEach((downloader, index) => {
            if (downloader.centerStatus === 2) {
                currentDownloadIds.push(downloader.downloaderId);
            }
        });
        return currentDownloadIds;
    }

    /**
     * 寻找下几个待下载的index
     * @param count 下几个（数量）
     * @return {array}
     */
    findNextDownloadDownloader(count) {
        let nextDownloader = [];
        for (let i = 0; i < this.setDownloaders.length; i++) {
            if (nextDownloader.length >= count) {
                break;
            } else {
                if (this.setDownloaders[i].centerStatus === 0) {//初始化成功
                    nextDownloader.push(this.setDownloaders[i]);
                }
            }
        }
        return nextDownloader;
    }

    /**
     * 初始化视图表格
     */
    initDownloadingTable() {
        let _this = this;
        if (_this.setDownloaders && _this.setDownloaders.length > 0) {
            _this.downloadingTable = [];
            _this.setDownloaders.forEach((downloader, index) => {
                let downloadInfo = downloader.downloaderInfo;
                _this.downloadingTable.push({
                    name: downloadInfo.lessonName,
                    publisher: downloadInfo.publisherName,
                    book: downloadInfo.bookName,
                    id: downloader.downloaderId,
                    status: downloader.centerStatus,
                    progress: 0,
                    isChecked: false
                });
            });
        }
    }

    /**
     * 触发下载列表的事件
     * @param index 索引，数组的第几个元素
     * @param value 需要改变的值
     * @param type 操作类型
     */
    touchDownloaderEvent(index, value, type) {
        console.log("touchDownloaderEvent callback index:: " + index + " value:: " + JSON.stringify(value) + " type::" + type)
        let _this = this;
        let downloaderEvent = new CustomEvent('setDownloader', {
            detail: {
                index: index,
                value: value,
                type: type //1.add = push  2.remove = splice 3.change = splice
            }
        });
        if (window.dispatchEvent) {
            window.dispatchEvent(downloaderEvent);
        } else {
            window.fireEvent(downloaderEvent);
        }
    }

    /**
     * 当前的课程是否正在下载
     * @param lessonId
     * @return {boolean}
     */
    lessonIsDownloading(lessonId) {
        let _this = this;
        let isDownloading = false;
        for(let i = 0; i < _this.setDownloaders.length; i ++){
            if (_this.setDownloaders[i].downloaderId === lessonId) {
                isDownloading = true;
                break;
            }
        }
        return isDownloading;
    }

    /**
     * 是否允许加入下载队列
     * @param param
     */
    isDownloaderAlowed(param){
        let _this = this;
        let result = true;
        for(let i = 0; i < _this.downloaded.length; i++){
            if(_this.downloaded[i].lessonId === param.SetDownloadId && param.ActionStatus === "0"){//如果是下载状态，且出现在已经下载过的列表里，不允许加入
                result = false;
                break;
            }
        }
        return result;
    }

    /**
     * 返回当前正在下载和已经完成下载的课程id
     */
    getCurrentDownloadLesson(){
        let downloadIds = [];
        DownloadCenter.getInstance().downloaded.forEach(down => {
            downloadIds.push(down.lessonId);
        });
        DownloadCenter.getInstance().setDownloaders.forEach(downloader => {
            downloadIds.push(downloader.downloaderId);
        });
        return downloadIds;
    }

    /**
     * 返回当前正在下载的课程
     * @return {Array}
     */
    getCurrentDownloadingLesson(){
        let downloadIds = [];
        DownloadCenter.getInstance().setDownloaders.forEach(downloader => {
            downloadIds.push(downloader.downloaderId);
        });
        return downloadIds;
    }

    /**
     * 接口的资源转为需要的资源类型
     * @param resType
     * @return {*}
     */
    resTypeToName(resType) {
        resType = DownloadCenter.getInstance().constVar.global.resourceSwitch[resType];
        return DownloadCenter.getInstance().constVar.global.resourceType[resType];
    }

    resTypeToEnName(resType){
        return DownloadCenter.getInstance().constVar.global.resourceSwitch[resType];
    }

    recordUserDownloadInfo(param){
        this.request.createUserDownloadInfoRecord(param).then((response) => {
            console.log("资源埋点=>资源下载完成::" + JSON.stringify(param));
        }).catch(error => {
            console.log("资源埋点=>资源下载失败");
        })
    }
}
